#include "Appender.h"
#include "Logger.h"
#include <sstream>
#include <time.h>

namespace phnq
{
	namespace kit
	{
		namespace log
		{
			Appender::Appender()
			{
				// a little constructor action
			}

			Appender::~Appender()
			{
				// a little destructor action
			}

			void Appender::append(Logger *logger, short level, LoggerTime t, char *chars)
			{
				stringbuf buf;
				time_t now;
				char tBuf[80];

				time(&now);
				struct tm *timeinfo;
				timeinfo = localtime(&now);
				strftime (tBuf, 80, "%Y-%m-%d %X", timeinfo);
				
				
				string levelStr;
				switch(level)
				{
					case Logger::DEBUG:
						levelStr = "DEBUG";
						break;
					case Logger::INFO:
						levelStr = "INFO";
						break;
					case Logger::WARNING:
						levelStr = "WARNING";
						break;
					case Logger::ERROR:
						levelStr = "ERROR";
						break;
					case Logger::CRITICAL:
						levelStr = "CRITICAL";
						break;
				}

				if(t)
				{
					float ms = 1000 * (float)t / (float)CLOCKS_PER_SEC;
					sprintf(lineBuf, "%s [%s] %s (%0.3fms) - %s", tBuf, logger->getCategory().c_str(), levelStr.c_str(), ms, chars);
				}
				else
				{
					sprintf(lineBuf, "%s [%s] %s - %s", tBuf, logger->getCategory().c_str(), levelStr.c_str(), chars);
				}
				
				appendLine(lineBuf);
			}

			StdOutAppender* StdOutAppender::getInstance()
			{
				static StdOutAppender instance;

				return &instance;
			}

			void StdOutAppender::appendLine(char *chars)
			{
				cout << chars << endl;
			}
		}
	}
}
